package at.guigu.web;

import at.guigu.pojo.User;
import at.guigu.service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    //1 创建一个私有的UserService对象
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //2 接收用户信息：获取用户名和密码以及获取复选框数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
        //获取程序自动生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        //验证验证码是否正确：此处忽略大小写
        if (!checkCodeGen.equalsIgnoreCase(checkCode)) {
            //如果不一样则不允许注册，即注册失败
            //将错误信息存储到request域中
            request.setAttribute("register_msg", "验证码错误，请重新输入");
            //跳回到用户登录页面即register.jsp
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;//结束执行本java文件中的后续代码
        }
        //3 调用Service注册用户
        Boolean flag = userService.register(user);
        //4 判断是否注册成功
        if (flag) {//注册成功
            request.setAttribute("login_msg", "注册成功，请登录");
            //跳回到用户登录页面即login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {//注册失败
            //将错误信息存储到request域中
            request.setAttribute("register_msg", "用户名重复");
            //跳回到用户登录页面即login.jsp
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}